<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SSE Disconnect Example</title>
</head>

<body>
    <h1>实时消息</h1>
    <button id="subscribeButton">订阅</button>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <button id="disconnectButton">断开连接</button>
    <div id="messages"></div>

    <script>
    	let eventSource;
        const id = 'a111';

        // 订阅按钮点击事件
        document.getElementById('subscribeButton').addEventListener('click', function () {
            eventSource = new EventSource('/sse/subscribe/' + id);

            eventSource.onmessage = function (event) {
                const messagesDiv = document.getElementById('messages');
                const newMessage = document.createElement('p');
                newMessage.textContent = `Received message: ${event.data}`;
                messagesDiv.appendChild(newMessage);
            };

            eventSource.onerror = function (error) {
                console.error('EventSource failed:', error);
                eventSource.close();
            };
        });

        // 断开连接按钮点击事件
        document.getElementById('disconnectButton').addEventListener('click', function () {
            if (eventSource) {
                fetch('/sse/disconnect/' + id, {
                    method: 'DELETE'
                })
               .then(response => response.text())
               .then(data => {
                    console.log(data);
                    eventSource.close();
                })
               .catch(error => {
                    console.error('请求断开连接时出错:', error);
                });
            }
        });
    </script>
</body>

</html>